package model

import (
	"errors"
	"gin/common/types"
	"gin/database"
	teamones_helper "github.com/teamones-open/go-helper"
	"strings"
	"time"
)

type PanUser struct {
	Id                 uint64           `json:"id" gorm:"column:id"`
	BaiduUid           uint64           `json:"baidu_uid" gorm:"column:baidu_uid"`
	BaiduName          string           `json:"baidu_name" gorm:"column:baidu_name"`
	NetdiskName        string           `json:"netdisk_name" gorm:"column:netdisk_name"`
	AvatarUrl          string           `json:"avatar_url" gorm:"column:avatar_url"`
	VipType            int              `json:"vip_type" gorm:"column:vip_type;default:0"`
	UkId               int64            `json:"uk" gorm:"column:uk"`
	ExpiryTime         types.TstampTime `json:"expiry_time" gorm:"column:expiry_time"`
	Created            types.TstampTime `json:"created" gorm:"column:created"`
	TenantId           int64            `json:"tenant_id" gorm:"column:tenant_id"`
	ExpiresIn          int64            `json:"expires_in" gorm:"column:expires_in"`
	AccessToken        string           `json:"access_token" gorm:"column:access_token"`
	RefreshToken       string           `json:"refresh_token" gorm:"column:refresh_token"`
	Scope              string           `json:"scope" gorm:"column:scope"`
	FailedRefreshToken int              `json:"failed_refresh_token" gorm:"column:failed_refresh_token;default:0"`
	UnionId            uint64           `json:"union_id" gorm:"column:union_id"`
	LinkType           string           `json:"link_type" grom:"type:enum('user','tenant');default:user"`
	IsAuthorize        uint             `json:"is_authorize" gorm:"column:is_authorize"`
	CookiesExpireAt    int64            `json:"cookies_expire_at" gorm:"column:cookies_expire_at"`
	IsDefault          string           `json:"is_default" gorm:"type:enum('yes','no');default:no"`
	Cookies            string           `json:"cookies" gorm:"type:text"`
}

// 设置表名
func (PanUser) TableName() string {
	return "pan_user"
}

// 插入百度网盘账户
func (this *PanUser) Insert() (id uint64, err error) {
	result := Mysql.DB.Create(&this)
	id = this.Id
	if result.Error != nil {
		err = result.Error
		return
	}
	return
}

// 更新百度网盘账户信息
func (this *PanUser) Update() (err error) {
	if this.Id > 0 {
		resultUpdate := Mysql.DB.Save(&this)
		if resultUpdate.Error != nil {
			err = resultUpdate.Error
			return
		}
	} else {
		err = errors.New("ID must exist.")
	}

	return
}

// 通过id查询一条用户数据
func (this *PanUser) FindById(Id uint64) (resData PanUser, err error) {
	resultFind := Mysql.DB.Where("id = ?", Id).First(&resData)

	if resultFind.Error != nil {
		err = resultFind.Error
		return
	}

	if resData.Id <= 0 {
		err = errors.New("User does not exist.")
	}
	return
}

// 通过baidu_name查询一条用户数据
func (this *PanUser) FindByBaiduName(baiduName string) (resData PanUser, err error) {
	resultFind := Mysql.DB.Where("baidu_name = ?", baiduName).First(&resData)

	if resultFind.Error != nil {
		err = resultFind.Error
		return
	}

	if resData.Id <= 0 {
		err = errors.New("User does not exist.")
	}
	return
}

// 查找还有三天内即将过期的用户数据
func (this *PanUser) FindExpiredInThreeDaysUser() (resData []PanUser, err error) {
	users := make([]PanUser, 0)
	db := Mysql.DB

	expiredInThreeDaysTime := time.Now().Unix() + 259200
	result := db.Where("expires_in < ?", expiredInThreeDaysTime).Where("failed_refresh_token <> ?", 1).Find(&users)

	if result.Error != nil {
		err = result.Error
		return
	}

	return users, err
}

// 通用查询一条数据
func (this *PanUser) Find(Param teamones_helper.SelectQueryParam) (resData PanUser, err error) {

	dataOne := new(PanUser)
	db := Mysql.DB

	// 组装过滤条件
	if Param.Where != nil {
		for key, val := range Param.Where {
			vals := val.(map[string]interface{})
			if strings.Contains(key, "bw_") {
				db = db.Where(vals["condition"], vals["val1"], vals["val2"])
			} else {
				db = db.Where(vals["condition"], vals["val"])
			}
		}
	} else {
		db = db.Where("?", "1=1")
	}

	// 应用分页
	db = db.Select(Param.Fields)

	result := db.First(&dataOne)
	if result.Error != nil {
		err = result.Error
		return
	}

	return *dataOne, err
}

// 通用获取多条数据
func (this *PanUser) Select(Param teamones_helper.SelectQueryParam) (total int, resData []PanUser, err error) {

	users := make([]PanUser, 0)
	db := Mysql.DB

	// 组装过滤条件
	if Param.Where != nil {
		for key, val := range Param.Where {
			vals := val.(map[string]interface{})
			if strings.Contains(key, "bw_") {
				db = db.Where(vals["condition"], vals["val1"], vals["val2"])
			} else {
				db = db.Where(vals["condition"], vals["val"])
			}
		}
	} else {
		db = db.Where("?", "1=1")
	}

	// 获取总条数
	db.Model(&PanUser{}).Count(&total)

	// 查找所有数据

	// 应用分页
	db = db.Select(Param.Fields).Limit(Param.Limit).Offset(Param.Offset)

	// 应用排序参数
	if Param.Order != "" {
		db = db.Order(Param.Order)
	}

	result := db.Find(&users)
	if result.Error != nil {
		err = result.Error
		return
	}

	return total, users, err
}
